<?php
declare (strict_types = 1);

namespace app\adminapi\middleware\http;
use adminmatrix\admin\service\JsonService;
use app\adminapi\cache\AdminAuthCache;
use think\helper\Str;
class AuthMiddleware
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        if(!$request->permission)
        {
           return $next($request);
        }

        if($request->adminInfo)
        {
            if (1 === $request->adminInfo['root'])
            {
                return $next($request);
            }

            $adminAuthCache = new AdminAuthCache($request->adminInfo['admin_id']);

            // 当前访问路径
            $accessUri = strtolower($request->rootUrl() . '/'. $request->pathinfo());
            // 全部路由
            $allUri = $this->formatUrl($adminAuthCache->getAllUri());
            // 判断该当前访问的uri是否存在，不存在无需验证
            if (!in_array($accessUri, $allUri)) {
                return $next($request);
            }

            // 当前管理员拥有的路由权限
            $AdminUris = $adminAuthCache->getAdminUri() ?? [];
            $AdminUris = $this->formatUrl($AdminUris);


            if (in_array($accessUri, $AdminUris)) {
                return $next($request);
            }
            return JsonService::fail("权限不足,无法访问操作" , httpCode:401);
        }

        return $next($request);
    }


    public function formatUrl(array $data)
    {
        return array_map(function ($item) {
            return strtolower(Str::camel($item));
        }, $data);
    }

}
